package com.yft.data.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yft.data.service.UserService;

@Controller
@RequestMapping("login")
public class LoginController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "userlogin", method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> userLogin(HttpServletRequest request,HttpSession session){
		logger.info("login");
		Map<String,Object> map = null;
		try {
			String username = ServletRequestUtils.getStringParameter(request,"username");
			String password = ServletRequestUtils.getStringParameter(request,"password");
			map = userService.getUserByNameAndPwd(username,password);
		} catch (ServletRequestBindingException e) {
			e.printStackTrace();
		}
		//查出用户放入session
		return map;
		
	}
	
	@RequestMapping(value = "user", method = RequestMethod.POST)
	public ModelAndView userLoginModel(HttpServletRequest request,HttpSession session){
		logger.info("login");
		Map<String,Object> map = null;
		try {
			String username = ServletRequestUtils.getStringParameter(request,"username");
			String password = ServletRequestUtils.getStringParameter(request,"password");
			map = userService.getUserByNameAndPwd(username,password);
		} catch (ServletRequestBindingException e) {
			e.printStackTrace();
		}
		//查出用户,角色和权限放入session
		List<Map<String,Object>> res = userService.getResourceByRole(Integer.parseInt(map.get("USERID").toString()));
		ModelAndView ma = new ModelAndView();
		ma.setViewName("index");
		ma.addObject("user", map);
		ma.addObject("resource", res);
		return ma;
		
	}
}